import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';

@Catch()
export class CommonFilter<T> implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status = exception?.getStatus() || 500; //获取状态码
    const exceptionResponse: any = exception?.getResponse() || '服务器异常'; //获取响应对象
    let msg = ''
    switch(typeof exceptionResponse){
      case "object":
        msg = (exceptionResponse?.error ?? 'error') + '|' + (exceptionResponse?.message ?? 'message')
        break;
      case "string":
        msg = exceptionResponse
        break;
    }
    //自定义的异常响应内容
    const msgLog = {
      code: status,
      timestamp: new Date().toLocaleString(),
      path: request.url,
      error: exceptionResponse,
      message: msg
    };

    response.status(status).json(msgLog);
  }
}
